package cn.javase.concurrent._设计模式._享元模式._自定义连接池;

import java.sql.Connection;
import java.util.concurrent.atomic.AtomicInteger;

public class Pool {

    private final int poolSize;                 // 连接池大小
    private Connection[] connections;           // 连接对象数组
    private AtomicInteger[] states;             // 连接状态数组，0表示空闲，1表示繁忙

    // 构造方法初始化
    public Pool(int poolSize) {
        this.poolSize = poolSize;
        this.connections = new Connection[poolSize];
        this.states = new AtomicInteger[poolSize];
        for (int i = 0; i < poolSize; i++) {
            connections[i] = new MockConnection();
        }
    }

    // 借连接
    public Connection borrow() {
        while (true) {
            for (int i = 0; i < poolSize; i++) {
                if (states[i].get() == 0) {
                    if (states[i].compareAndSet(0, 1)) {
                        return connections[i];
                    }
                }
            }
        }
    }

    /* TODO 自定义连接池还没有完成 */

}
